﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Produce.Result;

namespace Produce.Api.Filters
{
    public class MyFilter : IExceptionFilter
    {
        private readonly ILogger<MyFilter> logger;

        public MyFilter(ILogger<MyFilter> logger)
        {
            this.logger = logger;
        }

        /// <summary>
        /// 全局异常处理
        /// </summary>
        /// <param name="context"></param>
        public void OnException(ExceptionContext context)
        {
            // 获取简洁的错误信息
            var exception = context.Exception;
            string errorSource = context.ActionDescriptor.DisplayName ?? "未知位置";
            string errorType = exception.GetType().Name;
            string errorMessage = exception.Message;

            // 构建简洁的错误日志
            string logMessage = $"异常类型: {errorType}\n位置: {errorSource}\n错误信息: {errorMessage}";

            // 如果有内部异常，添加内部异常信息
            if (exception.InnerException != null)
            {
                logMessage += $"\n内部错误: {exception.InnerException.Message}";
            }

            // 记录日志
            logger.LogError(logMessage);

            // 创建简洁的API响应
            var result = new ApiResult<string>
            {
                Success = false,
                Message = errorMessage,
                Data = errorType
            };

            // 设置响应
            context.Result = new ObjectResult(result) { StatusCode = 500 };
            context.ExceptionHandled = true;
        }
    }
}
